package com.kobeliu.exceptions;

import com.kobeliu.result.GraceJSONResult;
import com.kobeliu.result.ResponseStatusEnum;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.SignatureException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
public class GraceExceptionHandler {

    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public GraceJSONResult resultMyCustomException(MyCustomException e){
        return GraceJSONResult.exception(e.getStatusEnum());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult resultMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errors = getErrors(bindingResult);
        return GraceJSONResult.errorMap(errors);
    }

    @ExceptionHandler({ExpiredJwtException.class,
                    SignatureException.class,
                UnsupportedJwtException.class,
            MalformedJwtException.class,
            io.jsonwebtoken.security.SignatureException.class
    })
    @ResponseBody
    public GraceJSONResult returnSignatureException(Exception e){
        e.printStackTrace();
        return GraceJSONResult.exception(ResponseStatusEnum.JWT_SIGNATURE_ERROR);
    }

    public Map<String,String> getErrors(BindingResult bindingResult){

        Map<String,String> map = new HashMap<>();

        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        for(FieldError f:fieldErrors){
            //错误对应 的属性字段名称
            String field = f.getField();
            //错误信息
            String msg = f.getDefaultMessage();

            map.put(field,msg);
        }

        return map;
    }
}
